import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'

export async function GET(request: NextRequest) {
  try {
    const user = getUserFromRequest(request)
    
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '20')
    const search = searchParams.get('search') || ''
    const author = searchParams.get('author') || ''
    const hasText = searchParams.get('hasText') || ''
    const dateRange = searchParams.get('dateRange') || ''

    const skip = (page - 1) * limit

    // 构建查询条件
    const where: any = {}
    
    // 搜索条件
    if (search) {
      where.OR = [
        { title: { contains: search } },
        { description: { contains: search } }
      ]
    }
    
    // 作者筛选
    if (author) {
      where.author = { contains: author }
    }
    
    // 时间范围筛选
    if (dateRange) {
      const now = new Date()
      let startDate: Date
      
      switch (dateRange) {
        case 'today':
          startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
          break
        case 'week':
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
          break
        case 'month':
          startDate = new Date(now.getFullYear(), now.getMonth(), 1)
          break
        default:
          startDate = new Date(0)
      }
      
      where.createdAt = { gte: startDate }
    }

    // 获取视频列表和总数
    const [videos, total] = await Promise.all([
      prisma.tikTokVideo.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
        select: {
          id: true,
          videoId: true,
          url: true,
          title: true,
          description: true,
          author: true,
          authorId: true,
          authorFollowers: true,
          authorFollowing: true,
          likes: true,
          shares: true,
          comments: true,
          views: true,
          duration: true,
          videoUrl: true,
          audioUrl: true,
          coverUrl: true,
          hashtags: true,
          musicTitle: true,
          musicAuthor: true,
          publishTime: true,
          localVideoPath: true,
          localAudioPath: true,
          localCoverPath: true,
          downloadStatus: true,
          downloadProgress: true,
          fileSize: true,
          createdAt: true,
          updatedAt: true,
          textExtractions: {
            select: {
              id: true,
              status: true,
              method: true,
              extractedText: true,
              confidence: true,
              language: true,
              createdAt: true
            },
            orderBy: {
              createdAt: 'desc'
            }
          },
          rewrittenTexts: {
            select: {
              id: true,
              originalText: true,
              rewrittenText: true,
              style: true,
              tone: true,
              length: true,
              requirements: true,
              createdAt: true
            },
            orderBy: {
              createdAt: 'desc'
            },
            take: 5 // 只取最新的5个改写结果
          }
        }
      }),
      prisma.tikTokVideo.count({ where })
    ])

    // 如果有文案状态筛选，需要在内存中过滤
    let filteredVideos = videos
    if (hasText === 'yes') {
      filteredVideos = videos.filter(video => video.textExtractions.length > 0)
    } else if (hasText === 'no') {
      filteredVideos = videos.filter(video => video.textExtractions.length === 0)
    }

    return NextResponse.json({
      videos: filteredVideos,
      pagination: {
        page,
        limit,
        total: hasText ? filteredVideos.length : total,
        pages: Math.ceil((hasText ? filteredVideos.length : total) / limit)
      }
    })

  } catch (error) {
    console.error('Get content videos error:', error)
    return NextResponse.json(
      { error: '获取视频列表失败' },
      { status: 500 }
    )
  }
}
